import { Component, OnInit, Input, SimpleChanges, OnChanges, Output, EventEmitter } from '@angular/core';
import { Tag } from '../../../../entity/tag.model';
import { TagService } from '../../../../service/tag.service';
import { ApplicationService } from '../../../../service/application.service';
import { TurbcomponentService } from '../../../../service/turbcomponent.service';
import { TurbComponent } from '../../../../entity/turbcomponent.model';
import { TagGroupItem } from '../tag-group-item';
import { List } from 'linqts';

@Component({
  selector: 'app-tag-selector',
  templateUrl: './tag-selector.component.html',
  styleUrls: ['./tag-selector.component.css']
})
export class TagSelectorComponent implements OnInit, OnChanges {
  /**
   * 型号Id数组
   * 
   * @type {number[]}
   * @memberof TagSelectorComponent
   */
  @Input() modelIds: number[] = [];
  /**
   * 移除的测点
   * 
   * @memberof TagSelectorComponent
   */
  @Input() removeTag: Tag;
  /**
   * 默认被选中的测点
   * 
   * @type {Tag[]}
   * @memberof TagSelectorComponent
   */
  @Input() selectTages: any[];
  /**
   * 限制测点选择数量
   * 默认:0
   * 0不做限制
   * @type {number}
   * @memberof DeviceSelectorComponent
   */
  @Input() choiceTagCount = 0;
  /**
   * 设置测点可用于那个模块
   * 默认：0
   * 趋势图	01
   * 矩阵	02
   * 结构图	03
   * 风机数据	04
   * 温度测点 05
   * @memberof TagSelectorComponent
   */
  @Input() tagSet = '0';
  /**
   * 是否展示
   * 
   * @memberof DeviceSelectorComponent
   */
  @Input() display = false;
  /**
   *
   *
   * @memberof TagSelectorComponent
   */
  @Input() selectedTagAll: boolean = false;
  /**
   * 选中的设备
   * 
   * @memberof DeviceSelectorComponent
   */
  @Output() selectedTagsChange = new EventEmitter<Tag[]>();


  public tagGroups: TagGroupItem[] = [];
  public choiceTagOver = false;

  tags: Tag[] = [];
  private turbComponents: TurbComponent[] = [];
  private timer: any = null;
  constructor(
    private tagService: TagService,
    private application: ApplicationService,
    private turbComponentService: TurbcomponentService) {
  }

  ngOnInit() {
  }
  ngOnChanges(changes: SimpleChanges): void {
    if (changes['modelIds'] != null && changes['modelIds'].currentValue != null) {
      this.loadTag(this.modelIds, this.tagSet);
    }
    if (changes['display'] != null && changes['display'].currentValue != null) {
      // 如果dispaly输入属性从ture变成false，表示设备选中项发生改变将触发输出selectedTagsChange属性
      if (!changes['display'].currentValue) {
        const checkedTags = this.getCheckedTags();
        this.selectedTagsChange.emit(checkedTags);
      }
    }
    if (changes['removeTag'] != null && changes['removeTag'].currentValue != null) {
      this.tags.forEach(tag => {
        if (tag.tagId == this.removeTag.tagId) {
          tag.isChecked = false;
          return;
        }

      });
    }
  }
  onAllTagChecked(checked: boolean) {

    if (checked === false) {
      this.tagGroups.forEach(group => group.tags.forEach(o => o.isChecked = false));
    } else {
      const checkedTags = this.getCheckedTags();
      this.tags.forEach(tag => {
        if (tag.isChecked === false) {
          if (this.choiceTagCount !== 0) {
            tag.isChecked = this.checkChoiceTagCount(tag, checkedTags);
          } else {
            tag.isChecked = true;
          }
        }
      });
    }
  }
  onGroupItemChecked(checked: boolean, tagGroupItem: TagGroupItem) {
    if (checked === false) {
      tagGroupItem.tags.forEach(tag => tag.isChecked = false);
    } else {
      const checkedTags = this.getCheckedTags();
      tagGroupItem.tags.forEach(tag => {
        if (tag.isChecked === false) {
          if (this.choiceTagCount !== 0) {
            tag.isChecked = this.checkChoiceTagCount(tag, checkedTags);
          } else {
            tag.isChecked = true;
          }
        }
      });
    }
  }
  /**
   * 单测点选择
   * 
   * @param {Event} event
   * @param {Device} device
   * @memberof DeviceSelectorComponent
   */
  onTagChecked(ev, tag: Tag) {
    const check: HTMLInputElement = ev.target;
    if (check.checked === false) {
      tag.isChecked = false;
    } else {
      if (tag.isChecked === false) {
        const checkedTags = this.getCheckedTags();
        if (this.choiceTagCount !== 0) {
          tag.isChecked = this.checkChoiceTagCount(tag, checkedTags, check);
          /* if (!tag.isChecked) {
            ev.stopPropagation();
            ev.preventDefault();
            return;
          } */
        } else {
          tag.isChecked = true;
        }
      }
    }
  }
  private loadTag(moduleIds: number[], tagSet: string) {
    this.tagGroups = [];
    this.tags = [];
    if (this.turbComponents.length <= 0) {
      Promise.all([
        this.turbComponentService.getTurbComponents(),
        this.tagService.getSelectorTags(tagSet, moduleIds)])
        .then(res => {
          this.turbComponents = [...res[0]];
          this.tags = [...res[1]];
          this.tagGroup(this.tags);
        });
    } else {
      this.tagService.getSelectorTags(tagSet, moduleIds)
        .then(res => {
          this.tags = [...res];
          this.tagGroup(this.tags);
        });
    }
  }
  private tagGroup(tags: Tag[]) {
    const tagList = new List(tags);
    const tagGroups = tagList.GroupBy(grouper => grouper.turbComponentId, map => map);
    const turbComponentIds = Object.getOwnPropertyNames(tagGroups);
    // 分组
    turbComponentIds.forEach(turbComponentId => {
      const tagGroupTags: Tag[] = tagGroups[turbComponentId];
      const index = this.turbComponents.findIndex(turbComponent => turbComponent.turbComponentId.toString() === turbComponentId);
      if (index !== -1) {
        tagGroupTags.forEach(tag => tag.turbComponentName = this.turbComponents[index].turbComponentName);
      }

      // 判断是否默认选中
      if (this.selectTages != null && this.selectTages.length > 0) {

        tagGroupTags.forEach(tag => {
          if (this.selectTages.findIndex(selectTag => selectTag === tag.tagKey) !== -1) {
            tag.isChecked = true;
          } else {
            tag.isChecked = false;
          }
        });
        const checkedTags = this.getCheckedTags();
        this.selectedTagsChange.emit(checkedTags);
      } else if (this.selectedTagAll) {

        tagGroupTags.forEach(tag => tag.isChecked = true);
        const checkedTags = this.getCheckedTags();
        this.selectedTagsChange.emit(checkedTags);
      } else {

        tagGroupTags.forEach(tag => tag.isChecked = false);
      }
      // 添加到测点分组
      this.tagGroups.push({
        title: index !== -1 ? this.turbComponents[index].turbComponentName : '',
        turbComponentId: parseInt(turbComponentId, 0),
        isChecked: false,
        tags: [...tagGroupTags]
      });
    });
  }
  private getCheckedTags(): Tag[] {
    const checkedTags: Tag[] = [];
    this.tags.forEach(tag => {
      if (tag.isChecked === true) {
        checkedTags.push(tag);
      }
    });
    return checkedTags;
  }
  private checkChoiceTagCount(tag: Tag, checkedTags: Tag[], check: HTMLInputElement = null): boolean {
    let result = true;
    // 限制选择设备数量
    if (this.choiceTagCount !== 0) {
      if (checkedTags.length + 1 > this.choiceTagCount) {
        result = false;
        if (this.choiceTagOver === false) {
          this.choiceTagOver = true;
          this.timer = setTimeout(() => {
            if (check != null) {
              check.checked = false;
            }
            this.choiceTagOver = false;
            clearTimeout(this.timer);
          }, 2000);
        }
      }
    }
    return result;
  }
}



// WEBPACK FOOTER //
// ./src/app/module/common/device-tag-selector/tag-selector/tag-selector.component.ts